import React, { useRef, useState, useEffect, useImperativeHandle, forwardRef } from 'react';
import { Divider, Button, Popconfirm, FormInstance, DatePicker, Pagination } from 'antd';
import { EditableProTable, ProColumns, ActionType } from '@ant-design/pro-table';
import { DownloadOutlined } from '@ant-design/icons';
import {
  getPayRecord,
  dropRecord,
  savePayInfo,
  getWorkerSum,
  downPayRecord
} from '@/services/human-resources/api';
import './style.less';
import {
  currentDate,
  formatDate,
  getDateValue,
  MsgType,
  parseDate2,
  showMsg,
  subtractDays,
  isNull,
  isExits,
  isSupportSticky
} from '@/utils/utils';
import { useModel } from 'umi';
import { ProFormFieldSet } from '@ant-design/pro-form';
import PermissionControl from '@/components/PermissionControl';
import moment from 'moment';

interface PayRecordProps {
  worker_id?: string;
  selectedOrder?: Array<Object>;
  totalMoney: string;
  onFinish: Function;
  onLoad: Function;
  isEdit: Function;
}

const PayRecord: React.FC<PayRecordProps> = forwardRef((props, ref) => {
  const { worker_id, selectedOrder, totalMoney, onFinish, onLoad, isEdit } = props;

  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();

  const [loading, setLoading] = useState<boolean>(false);
  const [searchParams, setSearchParams] = useState({});
  const [downloadFlag, setDownloadFlag] = useState<boolean>(false);


  // 汇总数据
  const [sum, setSum] = useState<HUMANRESOURCESAPI.WorkerSum>({
    total: 0,
    total_pay_price: 0,
    total_recom_price: 0,
    total_service_price: 0,
    min_pay_date: '',
    max_pay_date: '',
  });

  const { initialState } = useModel('@@initialState');
  // 编辑行
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  const [clickRow, setClickRow] = useState(''); // 当前选中的行编号，用于定位颜色

  const columns: ProColumns<HUMANRESOURCESAPI.PayItem>[] = [
    {
      title: '缴费日期',
      dataIndex: 'date',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <ProFormFieldSet>
            <DatePicker style={{ width: '100%' }} />
            <span style={{ padding: '0 5px' }}>-</span>
            <DatePicker style={{ width: '100%' }} />
          </ProFormFieldSet>
        );
      },
    },
    {
      title: '缴费单号',
      dataIndex: 'pay_id',
      width: 130,
      editable: false,
    },
    {
      title: '缴费时间',
      dataIndex: 'pay_time',
      valueType: 'dateTime',
      search: false,
      width: 160,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项是必填项',
          },
        ],
      },
      fieldProps: {
        style: {
          width: '100%',
        },
      },
      renderText: (val) => {
        // console.log('val', val, moment(val).format('YYYY-MM-DD hh:mm:ss'));
        return isNull(val)
          ? null
          : val.indexOf('-') > -1
          ? val
          : moment(val).format('YYYY-MM-DD hh:mm:ss');
      },
    },
    {
      title: '缴费金额',
      dataIndex: 'pay_price',
      valueType: 'money',
      width: 120,
      search: false,
      align: 'right',
      editable: false,
      // fieldProps: (form, { rowKey }) => {
      //   return {
      //     style: {
      //       width: '100%',
      //     },
      //     precision: 2,
      //     // formatter: value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ','),
      //     max: Number.MAX_SAFE_INTEGER,
      //     min: Number.MIN_SAFE_INTEGER,
      //     onChange: (value: any) => {
      //       console.log(value);
      //       if (isNaN(value)) {
      //         return;
      //       }
      //       if (value <= 0) {
      //         form.validateFields();
      //         return;
      //       }
      //     },

      //     onBlur: (e: any) => {
      //       const value = e.target.value;
      //       if (isNaN(value)) {
      //         return;
      //       }
      //       if (Number(value) <= 0) {
      //         form.validateFields();
      //         return;
      //       }
      //     }
      //   };
      // },
      // formItemProps: {
      //   rules: [
      //     {
      //       required: true,
      //       message: '此项是必填项',
      //     },
      //     {
      //       validator: (rule, value) => {
      //         if (value <= 0) {
      //           return Promise.reject(`金额输入有误`);
      //         }
      //         if (value > Number(sum.total_recom_price) - Number(sum.total_pay_price)) {
      //           return Promise.reject(
      //             `最多可输入${Number(sum.total_recom_price) - Number(sum.total_pay_price)}元`,
      //           );
      //         }
      //         return Promise.resolve();
      //       },
      //       message: `最多可输入${Number(Number(sum.total_recom_price) - Number(sum.total_pay_price)).toFixed(2)}元`,
      //     },
      //   ],
      // },
      // render: (_, entity) => {
      //   return `¥${entity.pay_price}`;
      // }
    },
    {
      title: '收费人',
      dataIndex: 'create_user_name',
      search: false,
      width: 120,
      editable: false,
    },
    {
      title: '收费人工号',
      dataIndex: 'create_user_id',
      search: false,
      width: 90,
      editable: false,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      width: 90,
      valueEnum: {
        N: '正常',
        D: '已作废',
      },
      editable: false,
    },
    {
      title: '操作',
      align: 'center',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : '',
      width: 120,
      valueType: 'option',
      render: (_, record) => {
        if (record.pay_id && record.status === 'N') {
          if (isExits('300300008')) {
            return [
              <Popconfirm
                key="void"
                title="您即将作废此记录，是否确认？"
                okText="确认作废"
                cancelText="再想想"
                onConfirm={async () => {
                  try {
                    await dropRecord(record.pay_id as string);
                    showMsg('已作废', MsgType.SUCCESS);
                    onLoad?.();
                    actionRef.current?.reload();
                    fetchSumInfo();
                  } catch (error) {
                    showMsg(error.data.errmsg);
                  }
                }}
              >
                <a>作废</a>
              </Popconfirm>,
            ];
          } else {
            return [];
          }
        }

        // 已作废
        if (record.status === 'D') {
          return '';
        }
        // 已改为不可修改，只能作废，先留着
        // return [
        //   <a
        //     key="modify"
        //     onClick={() => {
        //       actionRef.current?.startEditable(record.id || '');
        //     }}
        //   >
        //     修改
        //   </a>,
        // ];
        
      },
    },
  ];

  const [dataSource, setDataSource] = useState<HUMANRESOURCESAPI.PayItem[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [current, setCurrent] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(20);

  const [newRecord, setNewRecord] = useState({
    id: (Math.random() * 1000000).toFixed(0),
    create_user_name: initialState?.currentUser?.oper_name,
    create_user_id: initialState?.currentUser?.oper_id,
    status: 'N',
    pay_price: totalMoney,
  });

  // 导出 TODO
  const onExport = () => {
    console.log(123);
  };

  const fetchSumInfo = async () => {
    try {
      const data: HUMANRESOURCESAPI.WorkerSum = await getWorkerSum(worker_id as string);
      setSum(Object.assign({}, data));
      formRef.current?.setFieldsValue({
        date: [
          data.min_pay_date ? parseDate2(data.min_pay_date) : subtractDays(30),
          '',
          data.max_pay_date ? parseDate2(data.max_pay_date) : currentDate(),
        ],
      });
      fetchList({
        current,
        pageSize,
      });
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  };

  // 获取列表
  const fetchList = async (param) => {
    try {
      const [startDate, a, endDate] = formRef.current?.getFieldValue('date');
      const status = formRef.current?.getFieldValue('status');
      const params = {
        ...param,
        worker_id,
        begin_date: isNull(startDate) ? '' : startDate.format('YYYYMMDD'),
        end_date: isNull(endDate) ? '' : endDate.format('YYYYMMDD'),
        status,
      };
      setSearchParams(params);
      const data: HUMANRESOURCESAPI.PayItemList = await getPayRecord(params);
      setDownloadFlag(data.record_list.length > 0);
      const list = data.record_list?.map((item) => {
        return {
          ...item,
          id: item.pay_id,
        };
      });
      setTotal(data.sum_record_num || 0);
      setDataSource(list || []);
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  };

  useEffect(() => {
    if (worker_id) {
      fetchSumInfo();
    }
  }, [worker_id]);

  console.log('editableKeys', editableKeys)

  // 导出缴费记录
  const download = async() => {
    setLoading(true);
    await downPayRecord(searchParams).then(res => {
      setLoading(false);
      window.open(`/api/report/${res.file_token}/down`);
    }).catch(res => {
      setLoading(false);
    });
  }

  // 暴露的子组件方法，给父组件调用
  useImperativeHandle(ref, () => ({
    init: () => fetchSumInfo(),
  }))

  return (
    <div className="service-record">
      <div className="header">
        <div className="title">3.介绍费缴纳记录</div>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <div style={{ marginRight: 40 }}>
            介绍费总额：
            <span style={{ color: '#F5232D', fontWeight: 'bold' }}>{sum.total_recom_price}</span>元
          </div>
          <div style={{ marginRight: 40 }}>
            已收取：
            <span style={{ color: '#F5232D', fontWeight: 'bold' }}>{sum.total_pay_price}</span>元
          </div>
          <div style={{ marginRight: 40 }}>
            待收取：
            <span style={{ color: '#52C41A', fontWeight: 'bold' }}>
              {(Number(sum.total_recom_price) - Number(sum.total_pay_price)).toFixed(2)}
            </span>
            元
          </div>
        </div>
      </div>

      <Divider style={{ margin: '10px 0' }} />

      <EditableProTable<
        HUMANRESOURCESAPI.PayItem,
        COMMON.PageParams & { date?: Array<string>; begin_date?: string; end_date?: string }
      >
        formRef={formRef}
        actionRef={actionRef}
        manualRequest={true}
        search={{
          span: 8,
          optionRender: (searchConfig, formProps, dom) => {
            // console.log(formProps);
            return [
              <PermissionControl action_id="300300007">
                <Button key="export" type="primary" loading={loading} disabled={!downloadFlag} onClick={download} icon={<DownloadOutlined />}>导出查询结果</Button>
              </PermissionControl>,
              <Button
                key="query"
                type="primary"
                onClick={() => {
                  fetchList({
                    current,
                    pageSize,
                  });
                }}
              >
                查询
              </Button>,
            ];
          },
        }}
        rowKey="id"
        bordered
        dataSource={dataSource}
        columns={columns}
        value={dataSource}
        onChange={setDataSource}
        recordCreatorProps={isExits('300300009') ? {
          creatorButtonText: '新增缴费（需先核定并选定待收费服务记录）',
          disabled: isNull(selectedOrder),
          record: {
            id: (Math.random() * 1000000).toFixed(0),
            create_user_name: initialState?.currentUser?.oper_name,
            create_user_id: initialState?.currentUser?.oper_id,
            status: 'N',
            pay_price: totalMoney,
          },
        } : false}
        pagination={false}
        editable={{
          type: 'single',
          editableKeys,
          onChange: e => {
            setEditableRowKeys(e);
            isEdit(!isNull(e));
          },
          onSave: async (key, row) => {
            try {
              const params = {
                ...row,
                pay_time: formatDate(row.pay_time),
                service_ids: selectedOrder,
              };
              const data = Object.assign({}, params, { worker_id });
              // @ts-ignore
              await savePayInfo(data);
              showMsg('已保存', MsgType.SUCCESS);
              onFinish();
              // actionRef.current?.reload();
              fetchSumInfo();
              fetchList({
                current,
                pageSize,
              });
              return true;
            } catch (error) {
              showMsg(error?.data?.errmsg);
              // actionRef.current?.reset?.();
              return false;
            }
          },
        }}
        onRow={record => {
          return {
            onClick: event => { setClickRow(record.id) }, // 点击行
            onMouseEnter: event => {}, // 鼠标移入行
            onMouseLeave: event => {},
          };
        }}
        rowClassName={(record) => {
          return record.id === clickRow ? 'tableRowClick' : ''
        }}
      />
      <Pagination
        className="pay-pagination"
        pageSize={pageSize}
        showSizeChanger
        showQuickJumper
        total={total}
        showTotal={(total, range) => `第${range[0]}-${range[1]} 条 / 总共 ${total} 条`}
        onChange={(page, pageSize) => {
          setCurrent(page);
          fetchList({
            current: page,
            pageSize,
          });
        }}
        onShowSizeChange={(current, size) => {
          setCurrent(1);
          setPageSize(size);
          fetchList({
            current: 1,
            pageSize: size,
          });
        }}
        current={current}
      ></Pagination>
    </div>
  );
});
export default PayRecord;
